package com.kitchen.config;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库配置类 - 单例模式
 * 封装数据库连接配置
 */
public class DatabaseConfig {
    private static DatabaseConfig instance;
    private String url;
    private String username;
    private String password;
    
    private DatabaseConfig() {
        loadConfig();
    }
    
    public static synchronized DatabaseConfig getInstance() {
        if (instance == null) {
            instance = new DatabaseConfig();
        }
        return instance;
    }
    
    private void loadConfig() {
        Properties props = new Properties();
        try (InputStream is = getClass().getClassLoader().getResourceAsStream("db.properties")) {
            if (is != null) {
                props.load(is);
            } else {
                // 默认配置
                props.setProperty("db.url", "jdbc:mysql://localhost:3306/kitchen_order_system?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8");
                props.setProperty("db.username", "root");
                props.setProperty("db.password", "root");
            }
        } catch (IOException e) {
            // 使用默认配置
            props.setProperty("db.url", "jdbc:mysql://localhost:3306/kitchen_order_system?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8");
            props.setProperty("db.username", "root");
            props.setProperty("db.password", "root");
        }
        
        this.url = props.getProperty("db.url");
        this.username = props.getProperty("db.username");
        this.password = props.getProperty("db.password");
    }
    
    public Connection getConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new SQLException("MySQL驱动未找到", e);
        }
        return DriverManager.getConnection(url, username, password);
    }
    
    public String getUrl() {
        return url;
    }
    
    public String getUsername() {
        return username;
    }
}

